#!/usr/bin/env python
#
#    Copyright (C) 2003-2008 William Waites
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
Whois script, also supporting the Autonomous System metadata
cache.
"""
__usage__ = "%prog [options] resource"

__epilog__ = """
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
"""

from adjacencies.whois import WhoisServer, AutonomousSystemCache
from adjacencies.version import version
from optparse import OptionParser
import logging

__version__ = "%%prog %s" % (version,)

if __name__ == "__main__":
	logging.basicConfig(level=logging.DEBUG,
				format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
				datefmt='%Y/%m/%d %H:%M')

	opts = OptionParser(description=__doc__, usage=__usage__, 
				epilog=__epilog__, version=__version__)
	opts.add_option("--server", "-s", default="whois.arin.net")
	opts.add_option("--port", "-p", default=43)
	opts.add_option("--asn", "-a", action="store_true", default=False,
				help="Run in AS cache mode")
	opts.add_option("--cache", "-c", default=None,
				help="Cache to use in AS cache mode")
	opts.add_option("--debug", "-d", action="store_true", default=False,
				help="Debug mode")
	(vals, args) = opts.parse_args()
	
	if len(args) != 1:
		opts.print_help()
		exit()

	if vals.asn:
		ascache = AutonomousSystemCache(debug=vals.debug)
		print ascache[args[0]]
		exit()

	s = WhoisServer(vals.server, int(vals.port))
	try:
		result = s.query(*args)
		print result
	except:
		pass
